package com.teamblueplus.comicmaker;

import java.io.BufferedReader;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;

import java.util.ArrayList;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.teamblueplus.R;

import com.teamblueplus.websearch.GridViewImageAdapter;

/**
 * This class handles the default object window, which displays all the
 * preloaded images that comes with the app
 * 
 * 
 * @author hanzen
 */
public class AddDefaultObject extends Activity implements OnItemClickListener {

	private static int DEFAULT_NUMBER = 256;
	// private ListView listViewImages;
	private GridView gridViewImages;
	private EditText txtSearchText;

	private DefaultObjectGridViewAdapter adapter;
	private ArrayList<Bitmap> listImages;
	private Activity activity;

	String strSearch = null;
	ImageView image_view;
	Bitmap bitmap;

	private String selectedImagePath;
	static private ExportBitmapToFile saveFile;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.gridview_default);

		Log.d("h2", "addDefaultObject Started");
		activity = this;
		gridViewImages = (GridView) findViewById(R.id.gridViewDefault);

		txtSearchText = (EditText) findViewById(R.id.txtViewSearch);
		image_view = (ImageView) findViewById(R.id.imageview);

		listImages = new ArrayList<Bitmap>();
		new getImagesTask().execute();

	}

	public class getImagesTask extends AsyncTask<Void, Void, Void> {
		JSONObject json, json2;
		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			dialog = ProgressDialog.show(AddDefaultObject.this, "",
					"Please wait...");
		}

		@Override
		protected Void doInBackground(Void... params) {

			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 2;

			for (int i = 1; i <= DEFAULT_NUMBER; i++) {
				Bitmap temp = BitmapFactory.decodeResource(
						getResources(),
						getResources().getIdentifier("default_thumb" + i,
								"drawable", getPackageName()), options);
				listImages.add(temp);
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			setListViewAdapter(listImages);
		}
	}

	public void setListViewAdapter(ArrayList<Bitmap> images) {

		adapter = new DefaultObjectGridViewAdapter(activity, images);
		gridViewImages.setAdapter(adapter);
		gridViewImages.setOnItemClickListener(this);

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {

		Handler saveHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				setResult(RESULT_OK);
				saveFile = null;
				Intent intent = new Intent();
				intent.putExtra("path", selectedImagePath);
				setResult(RESULT_OK, intent);

				finish();
			}
		};

		Bitmap temp = BitmapFactory.decodeResource(
				this.getResources(),
				getResources().getIdentifier("default" + (pos + 1), "drawable",
						getPackageName()));
		saveFile = new ExportBitmapToFile(this, saveHandler, temp);
		saveFile.execute();

	}

	// static inner class for saving the bitmap
	private class ExportBitmapToFile extends AsyncTask<Intent, Void, Boolean> {
		private Context mContext;
		private Handler mHandler;
		private Bitmap nBitmap;

		public ExportBitmapToFile(Context context, Handler handler,
				Bitmap bitmap) {
			mContext = context;
			nBitmap = bitmap;
			mHandler = handler;
		}

		@Override
		protected Boolean doInBackground(Intent... arg0) {

			try {

				File sdCard = Environment.getExternalStorageDirectory();
				File dir = new File(sdCard.getAbsolutePath() + "/dimages");
				dir.mkdirs();

				selectedImagePath = System.currentTimeMillis()
						+ "defaultImg.jpg";
				File file = new File(dir, selectedImagePath);
				selectedImagePath = file.toString();

				final FileOutputStream out = new FileOutputStream(file);
				nBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
				out.flush();
				out.close();
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
			// mHandler.post(completeRunnable);
			return false;
		}

		@Override
		protected void onPostExecute(Boolean bool) {
			super.onPostExecute(bool);
			if (bool) {
				mHandler.sendEmptyMessage(1);
			}
		}
	}

}